package com.masiyi.sentinel.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@RestController
public class TestController {

    @GetMapping("/hello")
    public String hello() {

        try(Entry entry =  SphU.entry("testSentinel")) {
            return "hello sentinel";
        } catch (BlockException e) {
            e.printStackTrace();
            return "系统繁忙";
        }


    }

    @PostConstruct
    public void initFlowRules() {

        List<FlowRule> rules = new ArrayList<>();

        FlowRule flowRule = new FlowRule();

        flowRule.setResource("testSentinel");

        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);

        //限流一秒钟超过两次
        flowRule.setCount(2);

        rules.add(flowRule);

        FlowRuleManager.loadRules(rules);
    }
}
